﻿/**关于分厅调整的前端操作  author:WANGYY date:20181112**/
/**begin**/

var selectSource = new Object();
selectSource.FieldEnumDataIns = "CPOrganIns";
selectSource.FieldEnumDataSource= "select   [DepName] as text,  [DepId] as value  FROM[dbo].[CP_Dep] where (DepType=7   and DepState=1 ) and  ParentId ={0}   order by DepId";
//绑定基地信息
var url = "/api/HatchRoom/GetSourceInfo";
var selectObj = $(".selectChange");


var carNumberSource = new Object();
carNumberSource.FieldEnumDataIns = "CPYKWL";
carNumberSource.FieldEnumDataSource = "select a.CarNumber as [text],a.CarNumber as [value] from dbo.YW_TaskCarRelation a inner join dbo.YW_TaskOrderRelation b on a.TaskOrderId=b.Id  where b.OrderId='{0}' and b.GivetohallId={1}";
var carnumberObj = $(".selectCarNumber");

String.prototype.format = function () {
    if (arguments.length == 0) return this;
    for (var s = this, i = 0; i < arguments.length; i++)
        s = s.replace(new RegExp("\\{" + i + "\\}", "g"), arguments[i]);
    return s;

};
$(document).ready(function () {
    //初始化“孵化厅”下拉列表
    $.each(selectObj, function (index, eobj) {
        
        if (eobj.children.length === 1) {
            var baseid_id = eobj.id;
            var baseid = $("#" + baseid_id.replace("HallId", "BaseId")).val();
            var selectSou = new Object();
            selectSou.FieldEnumDataIns = selectSource.FieldEnumDataIns;
            selectSou.FieldEnumDataSource = selectSource.FieldEnumDataSource;
            selectSou.FieldEnumDataSource = selectSou.FieldEnumDataSource.format(baseid);    
            $.ajax({
                type: "POST",
                url: url,
                data: JSON.stringify(selectSou),
                contentType: 'application/json',
                success: function (data) {
                    if (data.length !== 0) {
                        //debugger;
                        //json字符串转化为json对象
                        data = eval('(' + data + ')');
                        data = eval('(' + data.Column + ')');
                        for (var i = 0; i < data.length; i++) {
                            var columnObj = data[i];
                            var html;
                            if (eobj.value === columnObj.valueEx)
                                html = "<option value ='" + columnObj.valueEx + "' selected='selected'> " + columnObj.textEx + "</option>";
                            else
                                html = "<option value ='" + columnObj.valueEx + "'> " + columnObj.textEx + "</option>";
                            $("#" + baseid_id).append(html);
                        }

                        $("#" + baseid_id + " option:first").remove();
                    }
                }
            });
        }
    });
    


    //select change事件
    $(".selectChange").on("change", function () {
        var evalue = $(this).val();
        var etext = $(this).find("option:selected").text();
        var id = $(this).attr("id");
        id = id.replace("HallId", "HallName");
        // $("#" + id).val(etext);
        // $(this).prepend("<input type='hidden' value='" + etext + "' id='" + id + "'>");
        $("#" + id).val(etext);
    });

    //对应车辆选择数据源绑定
    $.each(carnumberObj, function (eindex, eobj) {
        //debugger
        var orderid_id = eobj.id;
        var orderid = $("#" + orderid_id.replace("CarNumber", "OrderId")).val();
        var GivetohallId = $("#" + orderid_id.replace("CarNumber", "GivetohallId")).val();
        var selectcarNumber = new Object();
        selectcarNumber.FieldEnumDataIns = carNumberSource.FieldEnumDataIns;
        selectcarNumber.FieldEnumDataSource = carNumberSource.FieldEnumDataSource;
        selectcarNumber.FieldEnumDataSource = carNumberSource.FieldEnumDataSource.format(orderid, GivetohallId);    

        $.ajax({
            type: "POST",
            url: url,
            data: JSON.stringify(selectcarNumber),
            contentType: 'application/json',
            success: function (data) {
                if (data.length !== 0) {
                   // debugger;
                    //json字符串转化为json对象
                    data = eval('(' + data + ')');
                    data = eval('(' + data.Column + ')');
                    for (var i = 0; i < data.length; i++) {
                        var columnObj = data[i];
                        var html = "<option value ='" + columnObj.valueEx + "'> " + columnObj.textEx + "</option>";
                        $("#" + orderid_id).append(html);
                    }
                    
                }
            }
        });
    });



});



//保存及修改
var SaveAndUpdateData = function () {
    //debugger
    var inputObj = new Object();
    inputObj.Items = GetSelDataWhenUpdate();
    if (inputObj.Items.length <= 0) {
        alert("请选择要修改的数据！");
        return false;
    }
    inputObj.GridCode = CPGridGlobal_GridObj.GridCode;
    inputObj.CurUserId = CPCurUserId;
    inputObj.CurUserIden = CPCurUserIden;
    var updateUrl = CPWebRootPath + "/api/GridEngine/UpdateGridData";
    debugger
    var ADDItems = GetAddDataWhenSave();
    var Items = ReturnVerifyItem(inputObj.Items, ADDItems);  
    if (!verify(Items)) { alert("进雏数量+路耗数量+调整数量与孵化厅数量+路耗数量不符，请重新设置"); return false; }
    

    $.ajax({
        type: "POST",
        url: updateUrl,
        data: JSON.stringify(inputObj),
        contentType: 'application/json',
        success: function (data) {
            if (data.Result == false) {
                alert("修改失败，详细信息：" + data.ErrorMsg);
                return false;
            }
            else {
                // debugger
                var url = CPWebRootPath + "/api/HatchRoom/SaveUpdateData";
                inputObj.ADDItems = ADDItems;
                $.ajax({
                    type: "POST",
                    url: url,
                    data: JSON.stringify(inputObj),
                    contentType: 'application/json',
                    success: function (data) {
                        alert("保存成功！");
                        CPGridRefresh();
                    }
                });
            }
        }

    });
};


function ReturnVerifyItem(item,additem) {
    var Items = new Array();
    $.each(item, function (iIndex, iObj) {
        var tmp = new Object;
        tmp.OrderChildId = iObj.OrderChildId;
        tmp.DataPK = iObj.DataPK;
        tmp.BuyChickCount = iObj.BuyChickCount;
        tmp.HallLossCount = iObj.HallLossCount;
        tmp.TotalCount = iObj.TotalCount;
        tmp.OrderRoadLoss = iObj.OrderRoadLoss;
        tmp.AdjustNumber = iObj.AdjustNumber;
        Items.push(tmp);
    });
    $.each(additem, function (aIndex, aObj) {
        var tmp = new Object;
        tmp.OrderChildId = aObj.OrderChildId;
        tmp.DataPK = aObj.Id;
        tmp.BuyChickCount = aObj.BuyChickCount;
        tmp.HallLossCount = aObj.HallLossCount;
        tmp.TotalCount = aObj.TotalCount;
        tmp.OrderRoadLoss = aObj.OrderRoadLoss;
        tmp.AdjustNumber = aObj.AdjustNumber;
        Items.push(tmp);
    });
    return Items;
}

function GetTaskCarDataWhenUpdate() {
    var Items = new Array();
    $.each($(".CPGridChkCss"), function (nIndex, nObj) {
        if ($(nObj).is(':checked')) {
            var tmp = new Object();
            tmp.DataPK = $(nObj).val();
            tmp.FieldNamCol = new Array();
            tmp.FieldValueCol = new Array();
            $.each(CPGridGlobal_GridObj.ColumnCol, function (cIndex, cObj) {
                if (cObj.FieldName == "HallId") {
                    tmp.FieldNamCol.push(cObj.FieldName);
                    tmp.FieldValueCol.push($("#CPGridEditControl_" + cObj.FieldName + "_" + tmp.DataPK).val());
                }
                if (cObj.FieldName == "HallName") {
                    tmp.FieldNamCol.push(cObj.FieldName);
                    tmp.FieldValueCol.push(($("#CPGridEditControl_HallId_" + tmp.DataPK).find("option:selected").text()).replace(/(^[\s\n\t]+|[\s\n\t]+$)/g, ""));
                }

                if (cObj.FieldName == "BuyChickCount"
                ) {
                    tmp.FieldNamCol.push("OrderChickCountInCar");
                    tmp.FieldValueCol.push($("#CPGridEditControl_" + cObj.FieldName + "_" + tmp.DataPK).val());
                }
                if (cObj.FieldName == "HallLossCount"
                ) {
                    tmp.FieldNamCol.push("HallLossCount");
                    tmp.FieldValueCol.push($("#CPGridEditControl_" + cObj.FieldName + "_" + tmp.DataPK).val());
                }
            });
            Items.push(tmp);
        }
    });
    return Items;
}


function GetTaskOrderDataWhenUpdate() {
    var Items = new Array();
    $.each($(".CPGridChkCss"), function (nIndex, nObj) {
        if ($(nObj).is(':checked')) {
            var tmp = new Object();
            tmp.DataPK = $(nObj).val();
            tmp.FieldNamCol = new Array();
            tmp.FieldValueCol = new Array();
            $.each(CPGridGlobal_GridObj.ColumnCol, function (cIndex, cObj) {
                if (cObj.FieldName == "HallId") {
                    tmp.FieldNamCol.push(cObj.FieldName);
                    tmp.FieldValueCol.push($("#CPGridEditControl_" + cObj.FieldName + "_" + tmp.DataPK).val());
                }
                if (cObj.FieldName == "HallName") {
                    tmp.FieldNamCol.push(cObj.FieldName);
                    tmp.FieldValueCol.push(($("#CPGridEditControl_HallId_" + tmp.DataPK).find("option:selected").text()).replace(/(^[\s\n\t]+|[\s\n\t]+$)/g, ""));
                }
            });
            Items.push(tmp);
        }
    });
    return Items;
}

function PKCarFieldName() {
    var Items = new Array();
    $.each($(".CPGridChkCss"), function (nIndex, nObj) {
        if ($(nObj).is(':checked')) {
            var tmp = new Object();
            tmp.dataPKArray = "";
            tmp.DataPK = "";
            $.each(CPGridGlobal_GridObj.ColumnCol, function (Index, Obj) {
                if (Obj.FieldName == "CarNumber" || Obj.FieldName =="OrderId") {
                    tmp.dataPKArray += $("#CPGridEditControl_" + Obj.FieldName + "_" + $(nObj).val()).val() + ",";
                    tmp.DataPK += Obj.FieldName + ",";
                }
            });
            tmp.DataPK = tmp.DataPK.substr(0, tmp.DataPK.length - 1);
            tmp.dataPKArray = tmp.dataPKArray.substr(0, tmp.dataPKArray.length - 1);
            Items.push(tmp);
        }
    });
    return Items;
}

function GetPKFieldName() {
    var Items = new Array();
    $.each($(".CPGridChkCss"), function (nIndex, nObj) {
        if ($(nObj).is(':checked')) {
            var tmp = new Object();
            tmp.dataPKArray = "";
            tmp.DataPK = "";
            $.each(CPGridGlobal_GridObj.ColumnCol, function (Index, Obj) {
                if (Obj.FieldName == "GivetohallId" ) {
                    tmp.dataPKArray += $("#CPGridEditControl_" + Obj.FieldName + "_" + $(nObj).val()).val() + ",";
                    tmp.DataPK += Obj.FieldName + ",";
                }
            });
            tmp.DataPK = tmp.DataPK.substr(0, tmp.DataPK.length - 1);
            tmp.dataPKArray = tmp.dataPKArray.substr(0, tmp.dataPKArray.length - 1);
            Items.push(tmp);
        }
    });
    return Items;
}

//修改项
function GetSelDataWhenUpdate() {
    var Items = new Array();
    $.each($(".CPGridChkCss"), function (nIndex, nObj) {
        if ($(nObj).is(':checked')) {
            var tmp = new Object();
            tmp.DataPK = $(nObj).val();
            tmp.FieldNamCol = new Array();
            tmp.FieldValueCol = new Array();
            $.each(CPGridGlobal_GridObj.ColumnCol, function (cIndex, cObj) {             
                if (cObj.ColumnType == 10
                    || cObj.ColumnType == 11
                    || cObj.ColumnType == 12
                    || cObj.FieldName == "HallId" || cObj.FieldName =="HallName"
                ) {
                    tmp.FieldNamCol.push(cObj.FieldName);
                    tmp.FieldValueCol.push($("#CPGridEditControl_" + cObj.FieldName + "_" + tmp.DataPK).val().replace(/(^[\s\n\t]+|[\s\n\t]+$)/g, ""));
                }               
            });
            tmp.BuyChickCount = $("#CPGridEditControl_BuyChickCount_" + tmp.DataPK).val();
            if (tmp.BuyChickCount == "") tmp.BuyChickCount = 0;
            tmp.HallLossCount = $("#CPGridEditControl_HallLossCount_" + tmp.DataPK).val();
            if (tmp.HallLossCount == "") tmp.HallLossCount = 0;
            var trobj = $(nObj).parents('tr')[0];
            tmp.TotalCount = $("#CPGridControl_buychick_" + tmp.DataPK)[0].innerText;
            tmp.OrderRoadLoss = $("#CPGridControl_LossCount_" + tmp.DataPK)[0].innerText;
            tmp.AdjustNumber = $("#CPGridControl_AdjustNumber_" + tmp.DataPK)[0].innerText;
            tmp.OrderChildId = $("#CPGridEditControl_OrderChildId_" + tmp.DataPK).val().replace(/(^[\s\n\t]+|[\s\n\t]+$)/g, "");
            tmp.Remarks = $("#CPGridEditControl_Remarks_" + tmp.DataPK).val();
            Items.push(tmp);
        }
    });
    return Items;
}

//新增项
function GetAddDataWhenSave() {
    var Items = new Array();
    $.each($(".addtr"), function (nIndex, nObj) {
        var tmp = new Object();
        var tdobj = $(this).parents('tr')[0].children;
        var RadioObj = $(this).parent().find("input[id^='CPGirdDiv_Chk_']");
        tmp.Id = parseInt(RadioObj.val());
        tmp.OrderId = $("#CPGridControl_OrderId_" + tmp.Id)[0].innerText;
        tmp.GoodsName = tdobj[5].innerText;
        var selectObj = $(tdobj[9]).find("select[id^='CPGridEditControl_HallId_']");
        tmp.HallId = selectObj.val();
        tmp.HallName = selectObj.find("option:selected").text();
        var BuyChickObj = $(tdobj[10]).find("input[id^='CPGridEditControl_BuyChickCount_']");
        if (BuyChickObj.val() === "")
            tmp.BuyChickCount = 0;
        else
            tmp.BuyChickCount = parseInt(BuyChickObj.val());
        var HallLossObj = $(tdobj[11]).find("input[id^='CPGridEditControl_HallLossCount_']");
        if (HallLossObj.val() === "")
            tmp.HallLossCount = 0;
        else
            tmp.HallLossCount = parseInt(HallLossObj.val());
        tmp.OrderChildId = $("#CPGridEditControl_OrderChildId_" + tmp.Id).val().replace(/(^[\s\n\t]+|[\s\n\t]+$)/g, "");
        tmp.TotalCount = tdobj[6].innerText;
        tmp.OrderRoadLoss = tdobj[7].innerText;
        tmp.AdjustNumber = tdobj[8].innerText;
        Items.push(tmp);

    });
    return Items;
}

//editor:WANGYY  date:20181129  desc:选中行新增行，初始化
function CPGridInsertPitchOnData() {
    debugger
    var inputObj = new Object();
    var that = this;
    inputObj.Items = CPGridGetCheckSelTRData();
    if (inputObj.Items.length==0) {
        alert("请选择要复制的数据！");
        return false;
    }
    inputObj.GridCode = CPGridGlobal_GridObj.GridCode;
    inputObj.CurUserId = CPCurUserId;
    inputObj.CurUserIden = CPCurUserIden;



    //添加行
    if (inputObj.Items.length > 0) {
        $.each(inputObj.Items, function (index, obj) {
            var tableObj = obj.tableObj;
            var nIndex = obj.RowNum;
            var newTR = obj.RowObj;
            if (tableObj === undefined) return;
            if (index > 0) nIndex += index;
            var $tr = tableObj.find('tr').eq(nIndex);


            $tr.after(newTR[0].outerHTML);
            tableObj.find('tr').eq(nIndex + 1).find('td').eq(0).append('<label style="color:blue" class="addtr">删除</label');
            tableObj.find('tr').eq(nIndex + 1).find('td').eq(0).find('input').css("display", "none");
            tableObj.find('tr').eq(nIndex + 1).find('td').eq(0).find('input').removeClass("CPGridRadioCss");
            tableObj.find('tr').eq(nIndex + 1).find('td').eq(0).attr("onclick", "deleteNewTR(this)");
        });
        
    }
}

//删除新增的行
function deleteNewTR(temp) {
    if (confirm('是否要删除本行数据？')) {
        $(temp).parents('tr').remove();
    }
}
//获取选中Check的值，获取行数据
function CPGridGetCheckSelTRData() {
    // debugger
    var Items = new Array();
    $.each($(".CPGridChkCss"), function (nIndex, nObj) {
        if ($(nObj).is(':checked')) {
            //if (Items.length > 0) return false;
            var tmp = new Object();
            tmp.DataPK = $(nObj).val();
            tmp.FieldNamCol = new Array();
            tmp.FieldValueCol = new Array();
            tmp.FieldState = new Array();
            tmp.RowObj = new Object();
            tmp.TableObj = new Object();
            $.each(CPGridGlobal_GridObj.ColumnCol, function (cIndex, cObj) {
                if (cObj.ColumnType == 4) {
                    tmp.FieldNamCol.push(cObj.FieldName);
                    tmp.FieldValueCol.push($("#CPGridEditControl_" + cObj.FieldName + "_" + Items.DataPK).val());
                    tmp.FieldState.push(cObj.IsShow);
                }
            });
            var trobj = $(nObj).parents('tr');//需要复制的行内容
            tmp.RowObj = trobj;
            var tableObj = $(nObj).parents('table');//需要新增数据的table对象           
            tmp.tableObj = tableObj;
            tmp.RowNum = nIndex;
            Items.push(tmp);
        } else {
            if (Items.RowObj != undefined && Items.RowObj.length > 0) return false;
            else return true;
        }
      
    });
    return Items;
}

//editor:WANGYY date:20181130 desc:选中要删除的行
function DeleteData() {
    //debugger
    var sValue = CPGridGetSelChkData();
    if (sValue == "") {
        alert("请选择要删除的数据！");
        return false;
    }
    if (confirm("确实要删除选中的数据吗？")) {
        var Url = CPWebRootPath + "/api/GridEngine/DeleteGridData?GridCode=" + CPGridGlobal_GridCode + "&CurUserId=" + CPCurUserId + "&CurUserIden=" + CPCurUserIden;
        Url += "&DataPks=" + sValue;
        //为了表达式，需要把URL里其它字段再加上
        //再加其它参数
        var sResultArray = CPGetQueryString();
        for (var mm = 0; mm < sResultArray.length; mm++) {
            var tempSarray = sResultArray[mm].split('=');
            if (tempSarray[0].toLowerCase() == "gridcode"
                || tempSarray[0].toLowerCase() == "curuserid"
                || tempSarray[0].toLowerCase() == "curuseriden"
                || tempSarray[0].toLowerCase() == "datapks"
            )
                continue;
            Url += "&" + sResultArray[mm];
        }
        $.getJSON(Url, function (data) {
            if (data.Result == false) {
                alert("删除失败，详细信息：" + data.ErrorMsg);
                return false;
            }
            else {
                var delurl = CPWebRootPath + "/api/HatchRoom/DeleteGridData";
                var inputObj = new Object();
                inputObj.Items = GetSelDataWhenUpdate();
                inputObj.GridCode = CPGridGlobal_GridObj.GridCode;
                inputObj.CurUserId = CPCurUserId;
                inputObj.CurUserIden = CPCurUserIden;

                $.ajax({
                    type: "POST",
                    url: delurl,
                    data: JSON.stringify(inputObj),
                    contentType: 'application/json',
                    success: function (deldata) {
                        if (deldata.Result == false) {
                            alert("删除失败，详细信息：" + deldata.ErrorMsg);
                            return false;
                        }
                        else {
                            alert("删除成功！");
                            CPGridRefresh();
                        }
                    }
                });
            }
            
        });
    }
}


//保存校验【验证孵化厅数量、孵化厅路耗】
function verify(Items) {
    debugger
    $("input[id^='CPGridEditControl_BuyChickCount_']").removeAttr("style");
    $("input[id^='CPGridEditControl_HallLossCount_']").removeAttr("style");
    if (Items === undefined) return false;
    var idValue = "",id=0, BuyChickCount = 0, HallLossCount = 0, mark = 0;
    var ChickItems = new Array();
    $.each(Items, function (nIndex, nObj) {
       // debugger;
        var tmp = new Object();
        if (idValue == nObj.OrderChildId) {
            HallLossCount += parseInt(nObj.HallLossCount);
            BuyChickCount += parseInt(nObj.BuyChickCount);
        }
        else {
            id = nObj.DataPK;
            idValue = nObj.OrderChildId;
            HallLossCount = parseInt(nObj.HallLossCount);
            BuyChickCount = parseInt(nObj.BuyChickCount);
        }
        if (HallLossCount + BuyChickCount != parseInt(nObj.TotalCount) + parseInt(nObj.OrderRoadLoss) + parseInt(nObj.AdjustNumber) && BuyChickCount != 0) {
            tmp.OrderChildId = $("#CPGridEditControl_OrderChildId_" + id).val();
           // tmp.HallLossCount = "CPGridEditControl_HallLossCount_" + id;
        } else ChickItems = RemoveArrayItem(ChickItems, $("#CPGridEditControl_OrderChildId_" + id).val());
        if (!$.isEmptyObject(tmp)) ChickItems.push(tmp);
    });
    if (ChickItems.length > 0) {
        $.each(ChickItems, function (cIndex, cObj) {
            $("input[value='" + cObj.OrderChildId + "']").parents('tr').find("input[id^='CPGridEditControl_BuyChickCount_']").css('background-color', '#d81e06');
            $("input[value='" + cObj.OrderChildId + "']").parents('tr').find("input[id^='CPGridEditControl_HallLossCount_']").css('background-color', '#d81e06');
            //$("input[id^='" + cObj.BuyChickCount + "']").css('background-color', '#d81e06');
            //$("input[id^='" + cObj.HallLossCount + "']").css('background-color', '#d81e06');
        });
        return false;
    } else return true;
}

//删除数组中的指定项
function RemoveArrayItem(items, value) {
    if (items === undefined) return false;
    var ChItems = new Array();
    ChItems = items;
    for (var i = 0; i < ChItems.length; i++) {
        if (ChItems[i].OrderChildId == value) items = items.splice($.inArray(value, items), i);
    }
   
    return items;
}
/**end**/